﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HYBYSoft.Company.Models;
using HYBYSoft.Company.WebSite.Helper;
using System.Text;

namespace HYBYSoft.Company.WebSite.Filter
{
    public class HandleExceptionFilterAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        CompanySiteEntities _dbContext = new CompanySiteEntities();

        /// <summary>
        /// 异常发生处理
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
            //设置异常已被处理
            filterContext.ExceptionHandled = true;

            //获得Cookie中的令牌信息
            HttpCookie token = filterContext.RequestContext.HttpContext.Request.Cookies[ConstDefinition.TOKEN_NAME];

            string currentUser = "匿名用户";
            if (token != null)
            {
                //对令牌信息进行拆分处理
                byte[] tokenByteArray = Convert.FromBase64String(token.Value);
                currentUser = (Encoding.UTF8.GetString(tokenByteArray)).Split('$')[1];
            }

            //TODO：可根据策略进行异常处理

            //创建异常对象
            ExceptionLog log = new ExceptionLog
            {
                ExceptionMessage = filterContext.Exception.InnerException == null ? filterContext.Exception.Message : filterContext.Exception.InnerException.Message,
                ExceptionCategory = filterContext.Exception.InnerException == null ? filterContext.Exception.GetType().FullName : filterContext.Exception.InnerException.GetType().FullName,
                ExceptionOperator = currentUser,
                ExceptionStackTrace = filterContext.Exception.InnerException == null ? filterContext.Exception.StackTrace : filterContext.Exception.InnerException.StackTrace,
                ThrowTime = DateTime.Now,
                ControllorName = filterContext.RouteData.Values["controller"].ToString(),
                ActionName = filterContext.RouteData.Values["action"].ToString()
            };

            //记录异常信息
            _dbContext.AddToExceptionLogs(log);
            _dbContext.SaveChanges();


            filterContext.Result = new ViewResult() { ViewName = "Error" };
            //判断是不是后台区域
            if (filterContext.RouteData.DataTokens["area"] != null
                && filterContext.RouteData.DataTokens["area"].ToString() == "Admin")
            {
                //页面重定向到后台错误页
                filterContext.Result = new RedirectResult(@"~\Admin\Management\Error");

                //清除Cookie信息
                HttpCookie cookie = new HttpCookie(ConstDefinition.TOKEN_NAME);
                cookie.Expires = DateTime.Now.AddDays(-1);
                filterContext.HttpContext.Response.AppendCookie(cookie);
            }

            base.OnException(filterContext);
        }

    }
}